package com.xs.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xs.common.JsonResult;
import com.xs.entity.Article;
import com.xs.entity.Record;
import com.xs.entity.Type;
import com.xs.entity.utils.CountAndDayCount;
import com.xs.service.ArticleService;
import com.xs.service.RecordService;
import com.xs.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private RecordService recordService;


    @Autowired
    private TypeService typeService;

    //新增数据
    @PostMapping
    public JsonResult<?> add(@RequestBody Article article){
        article.setTime(new Date());
        article.setCover(1);
        articleService.save(article);
        return JsonResult.success();
    }

    //分页根据cover查询所有数据
    @GetMapping("/pageCoverSreach")
    public JsonResult<?> pageCoverSreach(
            @RequestParam(defaultValue = "") Integer tid,
            @RequestParam(defaultValue = "") Integer uid,
            @RequestParam(defaultValue = "") Integer cover,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(defaultValue = "") String name){
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (tid!=null){
            queryWrapper.eq("tid",tid);
        }
        if (uid!=null){
            queryWrapper.eq("uid",uid);
        }
        if (cover!=null) {
            queryWrapper.eq("cover",cover);
        }
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        Page page = articleService.page(new Page<>(pageNum,pageSize), queryWrapper);
        //解决删除操作导致的分页BUG
        if (pageNum>page.getPages()){
            page=articleService.page(new Page<>(page.getPages(),pageSize),queryWrapper);
        }
        return JsonResult.success(page);
    }


    //推荐模块的菜谱数量查询
    @GetMapping("/recommandArticle/{uid}")
    public JsonResult<?> getAll(@PathVariable Integer uid){
        //判断用户是否登录
        if (uid!=0){
            //先判断用户是否有阅读的数据
            Integer count = recordService.CountByUid(uid);
            System.out.println(count);
            //数据存在
            if (count!=0){
                //查询用户阅读记录
                Integer tid = recordService.getCover(uid).getTid();
                System.out.println("12316543213:"+tid);
                //返回推荐菜谱数据
                return JsonResult.success(articleService.recommandArticle(tid));
            }
        }

        //用户为空或者与阅读记录为空
        return JsonResult.success(articleService.reArticle());
    }


    //查询公告文章
    @GetMapping("/announceArticle")
    public JsonResult<?> getAnnounce(){
        return JsonResult.success(articleService.announceArticle());
    }


    //根据id组删除
    @PostMapping("/deletes")
    public JsonResult<?> deleteByIds(@RequestBody List<Integer> ids){
        return  JsonResult.success(articleService.removeByIds(ids));
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteById(@PathVariable Integer id){
        articleService.removeById(id);
        return JsonResult.success();
    }


    //修改
    @PutMapping
    public JsonResult<?> updateById(@RequestBody Article article){
        articleService.updateById(article);
        return JsonResult.success();
    }


    //通过用户id拿到收藏文章的信息
    @GetMapping("/selectCollectionArticle/{uid}")
    public JsonResult<?> selectCollectionArticle(@PathVariable Integer uid){
        return JsonResult.success(articleService.selectCollectionArticle(uid));
    }

    //根据文章id查询文章信息
    @GetMapping("/{id}/{uid}")
    public JsonResult<?> selectById(@PathVariable("id") Integer id,@PathVariable("uid")Integer uid){
        Article data = articleService.getById(id);
        Type type = typeService.getByTid(data.getTid());
        data.setType(type.getAgetext());
        //阅读数加1
        data.setReadnumber(data.getReadnumber()+1);

        //将此次数据记录到表record里 用作推荐
        if (uid!=0){
            Record record=new Record();
            record.setUid(uid);
            record.setTid(data.getTid());
            record.setTime(new Date());
            //新增数据
            recordService.save(record);
        }
//        updateById(data);
        return JsonResult.success(data);
    }

    //文章详细页面里的作者推荐文章
    @GetMapping("/pageOfUsersArticle")
    public JsonResult<?> getByUid(@RequestParam Integer id){
        return JsonResult.success(articleService.findUsersArticleBynickname(id));
    }



    //获取文章总数以及当日文章数
    @GetMapping("/count")
    public JsonResult<?> countUser() throws ParseException {
        //获取总数量
        List<Article> row = articleService.list();
        List<String> time=new ArrayList<>();
        //创建时间转换器
        DateFormat df = new SimpleDateFormat("YYYY-MM-dd");
        for (Article user : row) {
            String format = df.format(user.getTime());
            time.add(format);
        }
        System.out.println(time);
        Date date = new Date();
        //获取当前时间的年月日
        String data = df.format(date);
        int count=0;

        for (String s : time) {
            if (s.equals(data)){
                count=count+1;
            }
        }

        //将数据打包
        CountAndDayCount rows=new CountAndDayCount();
        rows.setCount(articleService.count());
        rows.setDayCount(count);
        return JsonResult.success(rows);
    }
}
